package com.intexh.quickandroid.pay;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.intexh.quickandroid.R;
import com.intexh.quickandroid.utils.DialogUtils;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.ToastUtil;
import com.intexh.quickandroid.utils.ValidateUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * Created by zhangjiawei on 2017/11/23.
 */

public enum PayHelper {
    INSTANCE;

    public static final int ALI_PAY = 0;
    public static final int WECHAT_PAY = 1;
    public static final int BALANCE_PAY = 2;

    private PayListener mPayListener;

    //h5 直接传支付凭证
    public void weChatPay(Activity context, String orderInfo, PayListener payListener) {
        mPayListener = payListener;
        if (!ValidateUtils.isValidate(GsonUtils.getStringFromJSON(orderInfo, "appid"))) {
            mPayListener.payFail("wechat", "支付信息不可用");
            return;
        }
        String appId = GsonUtils.getStringFromJSON(orderInfo, "appid");
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, appId, false);
        PayReq payReq = new PayReq();
        payReq.appId = appId;
        payReq.timeStamp = GsonUtils.getStringFromJSON(orderInfo, "timestamp");
        payReq.prepayId = GsonUtils.getStringFromJSON(orderInfo, "prepayid");
        payReq.nonceStr = GsonUtils.getStringFromJSON(orderInfo, "noncestr");
        payReq.partnerId = GsonUtils.getStringFromJSON(orderInfo, "partnerid");
        payReq.sign = GsonUtils.getStringFromJSON(orderInfo, "sign");
        payReq.packageValue = GsonUtils.getStringFromJSON(orderInfo, "package");
        msgApi.sendReq(payReq);
    }


    public void aliPay(Activity context, String orderInfo, PayListener payListener) {
        mPayListener = payListener;
        String signStr = orderInfo;
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(context);
            Map<String, String> stringStringMap = alipay.payV2(signStr, true);
            PayResult payResult = new PayResult(stringStringMap);
            final String resultStatus = payResult.getResultStatus();
            context.runOnUiThread(() -> {
                handlerResult(resultStatus);
            });
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void handlerResult(String resultStatus) {
        switch (resultStatus) {
            case "9000":    //支付成功
                mPayListener.paySuccess("alipay");
                break;
            case "8000":    //正在处理政，支付结果（有可能支付成功），请查询商户订单列表的支付状态
                break;
            case "4000":    //订单支付失败
                mPayListener.payFail("alipay", "支付失败：4000");
                break;
            case "5000":    //重复请求
                mPayListener.payFail("alipay", "重复请求支付");
                break;
            case "6001":    //支付取消
                mPayListener.payCancel("alipay");
                break;
            case "6002":    //网络连接失败
                mPayListener.payFail("alipay", "支付失败，网络连接失败，请检查您的网络连接");
                break;
            case "6004":    //支付结果位未知（有可能支付成功），请查询商户订单列表的支付状态
                break;
        }
    }


    public static void showPayTypeDialog(Context context, boolean isBanalcePay, OnPayChoseImpl impl) {
        final Dialog mBottomSheetDialog = new Dialog(context, R.style.MaterialDialogSheet);
        View view = View.inflate(context, R.layout.dialog_pay_sheet, null);
        view.findViewById(R.id.close_iv).setOnClickListener(v -> {
            mBottomSheetDialog.dismiss();
        });
        TextView aliPay_tv = view.findViewById(R.id.aliPay_tv);
        TextView wechatPay_tv = view.findViewById(R.id.wechatPay_tv);
        TextView balancePay_tv = view.findViewById(R.id.balancePay_tv);
        TextView payNow_tv = view.findViewById(R.id.payNow_tv);
        if (isBanalcePay) {
            balancePay_tv.setVisibility(View.VISIBLE);
            payNow_tv.setVisibility(View.VISIBLE);
        } else {
            balancePay_tv.setVisibility(View.GONE);
            payNow_tv.setVisibility(View.GONE);
        }
        final int[] type = {-1};
        aliPay_tv.setOnClickListener(v -> {
            type[0] = ALI_PAY;
//            if(!isBanalcePay){
//                impl.onChoose(type[0]);
//                mBottomSheetDialog.dismiss();
//            }
            aliPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ailipay, 0, R.mipmap.selected, 0);
            wechatPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.wechat_pay, 0, 0, 0);
            balancePay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.balance, 0, 0, 0);
        });
        wechatPay_tv.setOnClickListener(v -> {
            type[0] = WECHAT_PAY;
//            if(!isBanalcePay){
//                impl.onChoose(type[0]);
//                mBottomSheetDialog.dismiss();
//            }
            aliPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ailipay, 0, 0, 0);
            wechatPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.wechat_pay, 0, R.mipmap.selected, 0);
            balancePay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.balance, 0, 0, 0);
        });
        balancePay_tv.setOnClickListener(v -> {
            type[0] = BALANCE_PAY;
            aliPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ailipay, 0, 0, 0);
            wechatPay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.wechat_pay, 0, 0, 0);
            balancePay_tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.balance, 0, R.mipmap.selected, 0);
        });
        payNow_tv.setOnClickListener(v -> {
            if (type[0] == -1) {
                ToastUtil.showToast(context, "请选择支付方式");
                return;
            }
            impl.onChoose(type[0]);
            mBottomSheetDialog.dismiss();
        });
        mBottomSheetDialog.setContentView(view);
        mBottomSheetDialog.setCancelable(true);
        mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
        mBottomSheetDialog.show();
    }

    public interface OnPayChoseImpl {
        void onChoose(int type);
    }

    public static void showBalancePayDialog(Context context, DialogStringImpl impl) {
        View view = View.inflate(context, R.layout.dialog_balance_pay, null);
        ImageView close_iv = view.findViewById(R.id.close_iv);
        EditText password_et = view.findViewById(R.id.password_et);
        TextView payNow_tv = view.findViewById(R.id.payNow_tv);
        Dialog dialog = DialogUtils.showFullScreenViewDialog(context, view, false, false);
        close_iv.setOnClickListener(v -> {
            dialog.dismiss();
        });
        payNow_tv.setOnClickListener(v -> {
            String s = password_et.getText().toString();
            if (TextUtils.isEmpty(s)) {
                ToastUtil.showToast(context, "请输入支付密码");
                return;
            }
            if (s.length() < 6) {
                ToastUtil.showToast(context, "支付密码不能少于6位");
                return;
            }
            impl.onString(s);
            dialog.dismiss();
        });

    }

    public interface DialogStringImpl {
        void onString(String s);
    }

}
